/*
 * read.c
 *
 *  Created on: 2009-5-28
 *      Author: root
 */
#include "mysocket.h"
#include "msgtype.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

int readfromsocket(int sockfd,char *buf,int bufsize){
		msg message;
		msg retmsg;
		int i,rv;
		memset(&message,0,sizeof(msg));
		memset(&retmsg,0,sizeof(msg));
		message.mtype=MSG_USR_READ;
		message.pid=getpid();
		message.sock=sockfd;
		message.msgqid=processqid;
		message.buflen=bufsize;
		if((rv=msgsnd(tcpipstackqid,&message,sizeof(msg)-sizeof(long),IPC_NOWAIT))<0){
			fprintf(stderr,"tcp/ip stack does not work!\n");
			return -1;
		}
		if((rv=msgrcv(processqid,&retmsg,sizeof(retmsg)-sizeof(long),sockfd,0))<0){
			fprintf(stderr,"tcp/ip stack does not work!\n");
			return -1;
		}
		while(retmsg.buflen==-2){
			usleep(500000);
			if((rv=msgsnd(tcpipstackqid,&message,sizeof(msg)-sizeof(long),IPC_NOWAIT))<0){
				fprintf(stderr,"tcp/ip stack does not work!\n");
				return -1;
			}
			if((rv=msgrcv(processqid,&retmsg,sizeof(msg)-sizeof(long),sockfd,0))<0){
				fprintf(stderr,"tcp/ip stack does not work!\n");
				return -1;
			}
		}
		memcpy(buf,retmsg.buf,retmsg.buflen);
		return retmsg.buflen;
}
